package com.gfxy.modules.common.controller;

import com.gfxy.modules.base.entity.TeacherBaseInfo;
import com.gfxy.modules.base.service.ITeacherBaseInfoService;
import com.gfxy.modules.system.entity.*;
import com.gfxy.modules.system.service.*;
import com.gfxy.modules.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.ImportExcelUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: lijixin 2021/10/9 11:25 上午
 */
@Slf4j
@RestController
@RequestMapping("/import/user")
public class ImportUserController {

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserDepartService sysUserDepartsService;
    @Autowired
    private ISysUserDepartTeachingService sysUserDepartTeachingService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ITeacherBaseInfoService teacherBaseInfoService;

    @Autowired
    private ISysDictService sysDictService;

    private static final String USER_INFO_TYPE = "USER_INFO_TYPE";
    private static final String GFXY_TITLES_RANK = "GFXY_TITLES_RANK";
    private static final String USER_INFO_POSITION = "USER_INFO_POSITION";
    private static final String USER_INFO_DUAL_QUALIFICATION = "USER_INFO_DUAL_QUALIFICATION";

    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response)throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            InputStream inputstream = file.getInputStream();
            Workbook book = WorkbookFactory.create(inputstream);;

            List<SysDepart> departList = sysDepartService.list();

            Map<String,String> departMap = new HashMap<>();
            for (SysDepart sysDepart : departList) {
                departMap.put(sysDepart.getDepartName(),sysDepart.getId());
            }


            // 数据字典
            Map<String, String> teacherTypeMap = this.getTeacherTypeMap();
            Map<String, Integer> titlesRankMap = this.getTitlesRankMap();
            Map<String, Integer> positionMap = this.getPositionMap();
            Map<String, Integer> dualQualificationMap = this.getDualQualificationMap();


            Map<String,String> roleMap = new HashMap<>();
            roleMap.put("3-1", "1874841753573212162");
            roleMap.put("2-1", "1468832588804812801");
            roleMap.put("1-1", "1402832775044915202");

            try {
                Sheet sheet = book.getSheetAt(0);

                List<SysUser> sysUsersUpdate = new ArrayList<>();
                List<SysUser> sysUsersNew = new ArrayList<>();
                List<SysUserDepart> sysUserDepartsNew = new ArrayList<>();
                List<SysUserDepartTeaching> sysUserDepartTeachingsNew = new ArrayList<>();
                List<TeacherBaseInfo> teacherBaseInfos = new ArrayList<>();

                List<SysUserRole> sysUserRoles = new ArrayList<>();

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    SysUser sysUser = new SysUser();

                    String workNo = ExcelUtil.formatCell(row.getCell(0));

                    String name = ExcelUtil.formatCell(row.getCell(1));
                    String id = ExcelUtil.formatCell(row.getCell(2));



                    int gender = Integer.parseInt(id.substring(16,17));
                    String birthday = id.substring(6,14);
                    String orgName = ExcelUtil.formatCell(row.getCell(3));
                    String orgId = departMap.get(orgName);
                    if(orgId == null || orgId.isEmpty()){
                        System.out.print(name + " orgName " + orgName + " ");
                    }
                    String teachingOrgName = ExcelUtil.formatCell(row.getCell(4));
                    String teacherTypeStr = ExcelUtil.formatCell(row.getCell(5));
                    String titleStr = ExcelUtil.formatCell(row.getCell(6));
                    String positionStr = ExcelUtil.formatCell(row.getCell(7));
                    String dualQualificationStr = ExcelUtil.formatCell(row.getCell(8));


                    sysUser.setId(workNo);
                    sysUser.setPositionDescribe(positionStr);
                    sysUser.setTitleDescribe(titleStr);
                    sysUser.setTitleRank(titlesRankMap.get(titleStr));
                    sysUser.setTeacherType(teacherTypeMap.get(teacherTypeStr));
                    sysUser.setTeacherPosition(1);
                    sysUser.setWorkNo(workNo);
                    sysUser.setUsername(workNo);
                    sysUser.setRealname(name);
                    sysUser.setSex(gender % 2 == 1 ? 1:2);
                    String salt = oConvertUtils.randomGen(8);
                    sysUser.setSalt(salt);
                    String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), "Gfxy123456", salt);
                    sysUser.setPassword(passwordEncode);
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
                    sysUser.setBirthday(sdf.parse(birthday));
                    sysUser.setStatus(1);
                    sysUser.setDelFlag(CommonConstant.DEL_FLAG_0);

                    TeacherBaseInfo teacherBaseInfo = new TeacherBaseInfo();
                    teacherBaseInfo.setId(workNo);
                    teacherBaseInfo.setSex(gender % 2 == 1 ? 1:2);
                    teacherBaseInfo.setRealname(name);
                    teacherBaseInfo.setBirthday(sdf.parse(birthday));
                    teacherBaseInfo.setTeacherType(teacherTypeMap.get(teacherTypeStr));
                    teacherBaseInfo.setDualQualification(dualQualificationMap.get(dualQualificationStr));
                    teacherBaseInfo.setPosition(positionMap.get(positionStr));
                    teacherBaseInfo.setTitleRank(titlesRankMap.get(titleStr));
                    teacherBaseInfo.setStatus(2);
                    teacherBaseInfo.setDelFlag(CommonConstant.DEL_FLAG_0);

                    teacherBaseInfos.add(teacherBaseInfo);

                    sysUserDepartsNew.add(new SysUserDepart(sysUser.getId(),orgId));

                    if(teacherBaseInfo.getTeacherType().equals("1-1")){
                        sysUserDepartTeachingsNew.add(new SysUserDepartTeaching(sysUser.getId(),orgId));
                        sysUserRoles.add(new SysUserRole(sysUser.getId(),"1402832775044915202"));
                    } else {
                        if(!teachingOrgName.trim().isEmpty()){
                            String teachOrgId = departMap.get(teachingOrgName);
                            if(teachOrgId != null && !teachOrgId.isEmpty()){
                                sysUserDepartTeachingsNew.add(new SysUserDepartTeaching(sysUser.getId(),teachOrgId));

                            } else {
                                sysUserDepartTeachingsNew.add(new SysUserDepartTeaching(sysUser.getId(), "A05"));
                            }
                        } else {
                            sysUserDepartTeachingsNew.add(new SysUserDepartTeaching(sysUser.getId(), "A05"));
                        }
                    }

                    sysUsersNew.add(sysUser);

                    System.out.println(i);
                }

                log.debug("======================================================");
                log.debug("新增：" + sysUsersNew.size());

                sysUserService.saveBatch(sysUsersNew);
                sysUserDepartsService.saveBatch(sysUserDepartsNew);
                sysUserDepartTeachingService.saveBatch(sysUserDepartTeachingsNew);
                sysUserRoleService.saveBatch(sysUserRoles);
                teacherBaseInfoService.saveBatch(teacherBaseInfos);



            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines,successLines,errorMessage);
    }

    private Map<String, Integer> getDualQualificationMap() {
        Map<String,Integer> result = new HashMap<>();
        List<DictModel> list =  sysDictService.getDictItems(USER_INFO_DUAL_QUALIFICATION);
        for (DictModel model : list) {
            result.put(model.getText(), Integer.valueOf(model.getValue()));
        }
        return result;
    }

    private Map<String, Integer> getPositionMap() {
        Map<String,Integer> result = new HashMap<>();
        List<DictModel> list =  sysDictService.getDictItems(USER_INFO_POSITION);
        for (DictModel model : list) {
            result.put(model.getText(), Integer.valueOf(model.getValue()));
        }
        return result;

    }

    private Map<String, String> getTeacherTypeMap() {
        Map<String,String> result = new HashMap<>();
        List<DictModel> list =  sysDictService.getDictItems(USER_INFO_TYPE);
        for (DictModel model : list) {
            result.put(model.getText(), model.getValue());
        }
        return result;
    }


    private Map<String,Integer> getTitlesRankMap() {
        Map<String,Integer> result = new HashMap<>();
        List<DictModel> list =  sysDictService.getDictItems(GFXY_TITLES_RANK);
        for (DictModel model : list) {
            result.put(model.getText(), Integer.valueOf(model.getValue()));
        }
        return result;
    }



}
